<script lang="ts">
import { defineComponent, ref, reactive, watch, computed, watchEffect, onUnmounted } from "vue"
import { useI18n } from "vue-i18n";
import { UserModule } from "@/store/modules/user";
import { showToast, showDialog, showConfirmDialog } from 'vant';
import { getAssetsFile } from "@/utils/pub-use";
import { getUserInfo, getHFPriceList, getSellNFT, swap, buyNFT, getHFMax } from "@/api";
import { toStringMatch } from "@/utils/format";
import { NFTList } from "@/utils/nft"

export default defineComponent({
    setup() {
        const { t } = useI18n();
        const chartRefs = ref()
        const pageLoading = ref(true)
        const userInfo = ref({})
        const setat = reactive({
            pageNum: 0,
            pageSize: 20,
        });
        const refreshing = ref(false);
        const loading = ref(true);
        const finished = ref(false);
        const list = ref([]);
        const priceList = ref([]);
        const fromData = reactive({
            amount: "",
            pairType: ""
        })
        const fromList = ref([
            {
                icon: getAssetsFile("usdt.png"),
                name: "HF",
                price: 0,
                amount: 0,
            },
            {
                icon: getAssetsFile("usdt.png"),
                name: "USDH",
                price: 1,
                amount: 0,
            },
        ]);
        const fromItem = ref({
            icon: getAssetsFile("usdt.png"),
            name: "HF",
            price: 0,
            amount: 0,
        });
        const toItem = ref({
            icon: getAssetsFile("usdt.png"),
            name: "USDT",
            price: 0,
            amount: 0,
        });
        const swapToFrom = () => {
            let swapItem;
            swapItem = fromItem.value;
            fromItem.value = toItem.value;
            toItem.value = swapItem;
        };
        const getPrice = computed(() => {
            return toItem.value.name == "USDT"
                ? fromItem.value.price
                : 1 / toItem.value.price;
        });
        const onLoad = async () => {
            const res = await getSellNFT(setat);
            if (refreshing.value) {
                list.value = [];
                refreshing.value = false;
            }
            list.value = list.value.concat(res.data.data.NFTList || []);
            loading.value = false;
            setat.pageNum++;
            if (list.value.length >= res.data.data.Total) {
                finished.value = true;
            }
        };
        const onRefresh = () => {
            setat.pageNum = 0;
            finished.value = false;
            loading.value = true;
            refreshing.value = true
            onLoad();
        };
        const HFMax = ref(0)
        const HFprice = ref()
        const loadData = async () => {
            pageLoading.value = true
            userInfo.value = (await getUserInfo()).data.data.UserInfo || {}
            await getHFMax().then(res => {
                HFMax.value = Number(res.data.data.HFMax) - Number(userInfo.value.HF)
            })
            await getHFPriceList({ pageNum: 0, pageSize: 10000 }).then(res => {
                if (!fromItem.value.price) {
                    fromItem.value.price = res.data.data.HFprice
                    fromList.value[0].price = Number(fromItem.value.price);
                }
                HFprice.value = res.data.data.HFprice
                priceList.value = res.data.data.PriceList || [];
                chartRefs.value.initEcgarts(priceList.value);
            })
            pageLoading.value = false
        }
        const buySellType = computed(() => {
            const indxOf = fromItem.value.name + "/" + toItem.value.name;
            const pairTypeList = ["USDT/HF", "HF/USDT", "USDH/USDT"];
            return pairTypeList.indexOf(indxOf);
        });
        const sendSwap = () => {
            if (!Number(fromData.amount)) return
            // if (buySellType.value == 0 && Number(fromData.amount) > HFMax.value) {
            //     showToast(t("layout.MaximumPurchaseAmountOfHF") + HFMax.value)
            //     return
            // }
            showConfirmDialog({
                title: t('layout.exchange'),
                message: buySellType.value == 2 ? `${t('layout.needToSpend')}${toStringMatch(fromData.amount * 0.03 / fromList.value[0].price)}HF` : '',
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {
                            // if (userInfo.value.NFTV < Number(fromData.amount)) {
                            //     showToast(t("layout.theBalanceNFTVIsOnly") + userInfo.value.USDT);
                            //     return;
                            // }
                            await UserModule.verifyToken();
                            const res = await swap({
                                pairType: buySellType.value,
                                amount: fromData.amount,
                            })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                            } else {
                                if (buySellType.value == 0) {
                                    showToast(t("layout.MaximumPurchaseAmountOfHF") + HFMax.value)
                                } else {
                                    showToast(t('layout.YourHFIsNotEnoughPleaseRedeemIt'))
                                }
                            }
                            loadData()
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }
        const sendBuyNFT = ({ Price, Id }) => {
            showConfirmDialog({
                title: t('layout.Buy'),
                beforeClose: async function (action: string): Promise<boolean> {
                    if (action === "confirm") {
                        try {
                            if (userInfo.value.USDT < Number(Price)) {
                                showToast(t("layout.theBalanceUSDTIsOnly") + userInfo.value.USDT);
                                return;
                            }
                            await UserModule.verifyToken();
                            const res = await buyNFT({
                                id: Id,
                            })
                            if (res.data.code == 20) {
                                showDialog({ title: `${t("layout.success")}` })
                            } else {
                                showToast(res.data.message)
                            }
                            loadData()
                            onRefresh()
                        } catch (error) {
                            showToast(error)
                        }
                        return false;
                    } else {
                        return true;
                    }
                },
            }).catch(() => { });
        }
        const timer = ref();
        watchEffect(() => {
            timer.value = setInterval(async () => {
                userInfo.value = (await getUserInfo()).data.data.UserInfo || {}
            }, 1500);
        });
        onUnmounted(() => {
            clearInterval(timer.value);
        });
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    loadData();
                    onRefresh();
                }
            },
            { immediate: true }
        );
        return {
            pageLoading,
            fromData,
            fromItem,
            toItem,
            getPrice,
            fromList,
            list,
            refreshing,
            loading,
            finished,
            NFTList,
            userInfo,
            chartRefs,
            priceList,
            HFprice,
            loadData,
            onLoad,
            onRefresh,
            swapToFrom,
            toStringMatch,
            sendSwap,
            sendBuyNFT
        }
    }
})
</script>

<template>
    <div class="page">
        <div class="swap">
            <div class="swap-block">
                <div class="row">
                    <div class="iconInfo"
                        @click="fromItem.name != 'USDT' ? fromItem = fromList[fromItem.name == fromList[0].name ? 1 : 0] : false">
                        <img :src="fromItem.icon" alt="" srcset="" />
                        {{ fromItem.name }}
                        <van-icon name="play" v-if="fromItem.name != 'USDT'" />
                    </div>
                    <van-field v-model="fromData.amount" type="number" :placeholder="$t('layout.Pleaseenterquantity')" />
                </div>
                <img src="@/assets/image/swap.png" :style="{ opacity: fromItem.name != 'USDH' ? '1' : '0.2' }"
                    class="swapicon" alt="" @click="fromItem.name != 'USDH' ? swapToFrom() : false" srcset="">
                <div class="row">
                    <div class="iconInfo">
                        <img :src="toItem.icon" alt="" srcset="">
                        {{ toItem.name }}
                    </div>
                    <span>{{ toStringMatch(fromData.amount * getPrice) }}</span>
                </div>
            </div>
            <van-button type="primary" @click="sendSwap" :disabled="pageLoading">{{ $t('layout.exchange') }}</van-button>
        </div>
        <div class="logs" @click="$refs.swapLogs.onRefresh()"><img src="@/assets/image/image6.png">{{
            $t('layout.exchangeLogs') }}</div>
        <div class="balanceList">
            <div class="row">
                <div class="cell">
                    <div class="label">USDT</div>
                    <div class="value">{{ userInfo.USDT || 0 }}</div>
                </div>
                <div class="cell">
                    <div class="label">HF</div>
                    <div class="value">{{ userInfo.HF || 0 }}</div>
                </div>
            </div>
        </div>
        <div class="price-boxs">{{ HFprice || 0 }}</div>
        <Line-chart-mini ref="chartRefs" :chartData="priceList" />
        <div class="SellNFT">
            <div class="title">NFT{{ $t('layout.Sellorders') }}</div>
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                <van-list v-model:loading="loading" :finished="finished" :finished-text="$t('layout.noMore')"
                    @load="onLoad">
                    <div class="list">
                        <ul>
                            <li v-for="(item, index) in list" :key="index">
                                <div class="name"><i></i>{{ $t(`layout.${NFTList[item.NFTType].name}`) }}</div>
                                <img :src="NFTList[item.NFTType].image" alt="" srcset="">
                                <div class="text">{{ $t('layout.sellingprice') }}</div>
                                <div class="price">{{ item.Price }} USDT </div>
                                <van-button type="primary" @click="sendBuyNFT(item)">{{ $t('layout.Buy') }}</van-button>
                            </li>
                        </ul>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
    </div>
    <get-swap-list ref="swapLogs" />
</template>

<style lang="less" scoped>
.page {
    padding: 0 15px 15px 15px;

    .logs {
        padding: 20px 0 5px 0;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        color: #0BA662;

        img {
            margin-right: 8px;
            height: 15px;
        }
    }

    .balanceList {
        margin-top: 12px;
        border-radius: 6px;

        .row {

            .cell {
                margin-bottom: 8px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 45px;
                padding: 0 15px;
                background: #FFFFFF;
                border-radius: 6px;

                .value {
                    font-size: 15px;
                    font-weight: bold;
                    color: #0BA662;
                    letter-spacing: 1px;
                }
            }

        }
    }

    .price-boxs {
        padding: 20px 0 0 0;
        text-align: center;
        font-size: 16px;
        background: #FFFFFF;
    }

    .swap {
        border-radius: 10px;
        overflow: hidden;

        .swap-block {
            position: relative;

        }

        .swapicon {
            position: absolute;
            left: 0;
            right: 0;
            top: 50%;
            margin: -10px auto 0 auto;
            width: 20px;
            height: 20px;
        }

        .row {
            height: 90px;
            padding: 0 15px;
            background: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .iconInfo {
                display: flex;
                align-items: center;
                font-size: 18px;
                font-weight: 500;
                color: #1F2120;

                img {
                    margin-right: 10px;
                    width: 40px;
                    height: 40px;
                }

                .van-icon {
                    margin-left: 9px;
                    transform: rotate(90deg);
                }
            }

            .van-field {
                background: transparent;
                padding: 0;
                height: 50px;
                line-height: 50px;

                &:deep(input) {
                    text-align: right;
                    background: transparent;
                }
            }

            span {
                font-size: 18px;
                font-weight: bold;
                color: #11C299;
                line-height: 18px;
            }

            &:last-child {
                background: rgba(11, 166, 98, 0.05);
            }
        }

        .van-button {
            margin-top: 20px;
        }
    }

    .SellNFT {
        margin-top: 20px;

        .title {
            font-size: 16px;
            font-weight: bold;
        }

        .list {
            margin-top: 15px;

            ul {
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;

                li {
                    margin-bottom: 10px;
                    width: 169px;
                    padding: 4px 4px 16px 4px;
                    text-align: center;
                    box-sizing: border-box;
                    background: #FFFFFF;
                    border-radius: 8px;

                    .name {
                        padding: 10px 10px 10px 0;
                        font-size: 12px;
                        font-weight: 500;
                        text-align: left;
                        color: #0BA662;

                        i {
                            display: inline-block;
                            width: 6px;
                            height: 6px;
                            margin: 0 8px 0 10px;
                            border: 2px solid #0BA662;
                            box-sizing: border-box;
                            border-radius: 50%;
                        }
                    }

                    img {
                        display: block;
                        margin: 0 auto;
                        height: 135px;
                    }

                    .text {
                        margin-top: 12px;
                        color: #1F2120;
                    }

                    .price {
                        margin-top: 5px;
                        font-size: 20px;
                        font-weight: bold;
                        color: #0BA662;
                        line-height: 20px;
                    }

                    .van-button {
                        margin-top: 9px;
                        width: 153px;
                        height: 33px;
                        background: #0BA662;
                        box-shadow: 0px 0 10px 0px rgba(128, 48, 36, 0.1);
                        border-radius: 20px;
                    }
                }
            }
        }
    }
}
</style>
